<template>
    <div class="all">
        <el-card class="box-card">
            <!-- 头部区域 -->
            <div class="header">
                <div class="header-left">
                    <el-button type="primary" @click="dialogVisible = true">新增</el-button>
                    <el-button @click="delall">删除</el-button>
                </div>
                <div class="header-right">
                    <el-input class="input1" v-model="input" placeholder="请输入名称" />
                    <el-button @click="search" type="primary"><el-icon><Search /></el-icon>查询</el-button>
                    <el-button  @click="reset"><el-icon><RefreshLeft /></el-icon>重置</el-button>
                </div>
            </div>
            <!-- 表格区域 -->
            <el-table class="table" :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="图片" width="100">
                    <template #default="scope">
                        <el-image ref="previewImg" style="width: 50px;   height: 30px" :preview-src-list="[scope.row.picture]" :src="scope.row.picture" fit="contain" />
                        <!-- <img data-toggle="lightbox" :src="[scope.row.picture]" data-image="large-image.jpg" data-caption="小图看大图" class="img-thumbnail" alt="" width="200"> -->
                    </template>
                </el-table-column>
                <el-table-column label="名称" width="430">
                    <template #default="scope">
                        <el-popover
                            placement="bottom"
                            :width="370" 
                            trigger="click"
                            :content="scope.row.name"
                        >
                            <template #reference>
                                <el-text class="name">{{ scope.row.name }}</el-text>
                            </template>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column prop="date" label="创建时间" width="230" >
                    <template #default="scope">
                        {{ filterTime(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button link type="primary" @click="logs(scope.row)">编辑</el-button>
                        <el-button link  type='success' @click="previewPic">预览</el-button>
                        <el-button link  type='danger' @click="deleteMethod(scope.row.id)">删除</el-button>

                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="pagination-box">
                <div class="pagination-div"></div>
                <el-pagination class="pagination" background layout="prev, pager, next, jumper" 
                    :total="totalNum"
                    v-model:current-page="currentPage1"
                    :page-size="pageSize1"
                    @current-change="handleCurrentChange"
                />
            </div>
            <!-- 添加 -->
            <el-dialog
                v-model="dialogVisible"
                title="新增"
                width="35%"
                :before-close="handleClose"
            >
            <el-form :model="form"  :rules="rules"
                    ref="ruleFormRef" label-width="70px">
                <el-form-item label="图片" prop="picture">
                  
                    <el-upload
                        class="avatar-uploader"
                        action="/dev-api/api/uploadimg/"
                        :show-file-list="false"
                        :on-success="success"
                    >
                        <img v-if="form.picture" :src="form.picture" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="*名称" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
            </el-form>
                <template #footer>
                <span class="dialog-footer">
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                    保存
                    </el-button>
                </span>
                </template>
            </el-dialog>
            <!-- 修改数据 -->
            <el-dialog
                v-model="editDialogVisible"
                title="修改"
                width="35%"
                :before-close="handleClose"
            >
            <el-form 
            :rules="rules"
            ref="editRuleFormRef"
            :model="editObj"
            label-width="70px">
                <el-form-item label="图片" prop="picture">
                  
                    <el-upload
                        class="avatar-uploader"
                        action="/dev-api/api/uploadimg/"
                        :show-file-list="false"
                        :on-success="editSuccess"
                    >
                        <img v-if="editObj.picture" :src="editObj.picture" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="editObj.name" />
                </el-form-item>
            </el-form>
                <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editResetForm(editRuleFormRef)">取消</el-button>
                    <el-button type="primary" @click="editSubmitForm(editRuleFormRef)">
                    保存
                    </el-button>
                </span>
                </template>
            </el-dialog>
            <!-- 确认删除数据 -->
            <el-dialog
                v-model="deltrue"
                title="提示"
                width="30%"
                :before-close="handleClose"
            >
                <span>确定删除所选中的内容吗</span>
                <template #footer>
                <span class="dialog-footer">
                    <el-button @click="deltrue = false">取消</el-button>
                    <el-button type="primary" @click="delSum">
                    确定
                    </el-button>
                </span>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup>
import { ref,reactive } from 'vue'
import { 
    Search,
    RefreshLeft,
    Delete, 
    Download, 
    Plus, 
    ZoomIn
} from '@element-plus/icons-vue'
import moment from "moment"
import service from '@/utils/request.ts'
const previewImg=ref(null)
const previewPic=()=>{
    // previewImg.value.clickHandler();
}
const editRuleFormRef = ref()
//表单校验
const ruleFormRef = ref()
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible.value=false
}

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      addMethod()
    }
  })
}
//修改表单校验
const rules = reactive({
    picture: [
    { required: true, message: '请选择分类！', trigger: 'blur' },
  ],
  
  name:[{ required: true, message: '请输入名称！', trigger: 'blur' },]
})
const editResetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  editDialogVisible.value=false
}
const editSubmitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      editMethod()
    }
  })
}

const editDialogVisible  = ref(false)

const pageSize1 = ref(4)
const currentPage1 = ref(1)
const totalNum = ref(0)
const handleCurrentChange = (val)=>{
    currentPage1.value= val
    getDateList()
}
const editObj = reactive({
    picture:'',
    name:'',
    id:''
})
const editSuccess = (obj)=>{
    editObj.picture = obj.path
}
const editMethod = async ()=>{
    const {code,msg} =  await service.post('/api/collect/editcollectwriting/',editObj)
    if(code===200){
        ElMessage(msg)
    }else{
        ElMessage('修改失败')
    }
    editDialogVisible.value  =false
    getDateList()
}
const search =()=>{
    getDateList()
}
const delSum = async ()=>{
    const ids = truelist.value.map(item=>item.id)
    const {code,msg} =  await service.post('/api/collect/delallcollectwriting/',ids)
    if(code===200){
        ElMessage(msg)
    }else{
        ElMessage('删除失败!')
    }
    getDateList()
    deltrue.value=false
}
const deleteMethod = (id)=>{
    ElMessageBox.confirm(
    '确定删除？',
    '删除',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
        const {code,msg} =  await service.delete(`/api/collect/collectwriting/?id=${id}`)
        if(code==200){
            ElMessage({
                type: 'success',
                message: '删除数据成功',
            })
            getDateList()
        }else{
                ElMessage({
            type: 'info',
            message: 'Delete 失败',
        })
        }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}
const reset = ()=>{
    currentPage1.value = 1
    input.value = ''
    getDateList()
}
// 头部搜索输入框
let input = ref('')
// 过滤方法（格式化时间数据）
const filterTime = (time) => {
    return moment(time).format('YYYY-MM-DD HH:mm:ss')
}
const success = (obj)=>{
    form.picture = obj.path
}
// 表格数据
const tableData = ref([])
const getDateList = async ()=>{
   const {code,data,total} =  await service.get(`/api/collect/collectwriting/?page=${currentPage1.value}&size=${pageSize1.value}&name=${input.value}`)
   if(code===200){
        tableData.value =data
        totalNum.value = total
   }
}
onMounted(()=>{
    getDateList()
})
// 表格选中列表
const truelist = ref([])

const addMethod = async ()=>{
    const {code,msg} =await service.post('/api/collect/collectwriting/',form)
    dialogVisible.value = false
    if(code===200){
        ElMessage(msg)
        getDateList()
    }else{
        ElMessage('错误！')
    }
    form.picture = ''
    form.name = ''
}

// 点击选中触发函数
const handleSelectionChange = (val)=>{
    truelist.value=val
    console.log('执行',val);
}

// 删除选中区
const deltrue = ref(false)

const delall = ()=>{
    if(truelist.value.length===0){
        ElMessage({
            message: '请选中后操作',
            type: 'warning',
        })
    }else{
        deltrue.value=true
    }
}


// 添加区域功能
const dialogVisible = ref(false)

const handleClose = (done) => {
  ElMessageBox.confirm('您确定要关闭吗?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}
// 添加form
const form = reactive({
    picture:'',
    name: '',
})
// 图片上传区
const dialogImageUrl = ref('')
const dialogVisible2 = ref(false)
const disabled = ref(false)

const handleRemove = (file) => {
  console.log(file)
}





const logs = (val)=>{
    editDialogVisible.value=true
    editObj.picture = val.picture
    editObj.name = val.name
    editObj.id = val.id
}
</script>
<style>
.el-table .el-table__cell {
    z-index: auto !important;
}
</style>
<style lang="scss" scoped>
    .all{
        padding: 0 15px;
        .box-card{
            .header{
                display: flex;
                .header-left{
                    flex: 1;
                }
                .header-right{
                    .input1{
                        width: 200px;
                        margin-right: 15px;
                    }
                }
            }
            .pagination-box{
                margin-top: 20px;
                display: flex;
                .pagination-div{
                    flex: 1;
                }
            }
            .table{
                .name{
                    display: inline-block;
                    width: 320px;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                }
            }
        }
    }
    .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar{
    height: 100px;
    width: 100px;
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>